package com.ziq.zcamp.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.ziq.base.extension.dp

class PageLineIndicator @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    val backgroundPaint = Paint()
    val foregroundPaint = Paint()

    var centerY = 0f
    var backgroundHalfWidth = 0f
    var foregroundHalfWidth = 0f
    var pageCount = 0
    var pageIndex = 0
    private var forceFromStart = false //是否强制从起点开始

    init {
        updatePaint(setting = {backgroundPaint, foregroundPaint->
            backgroundPaint.strokeWidth = 2.dp.toFloat()
            backgroundPaint.setColor(Color.parseColor("#1FFFFFFF"))
            foregroundPaint.strokeWidth = 2.dp.toFloat()
            foregroundPaint.setColor(Color.parseColor("#00FFAB"))
        })
    }

    fun setForceFromStart(forceFromStart:Boolean){
        this.forceFromStart = forceFromStart
    }

    fun setPageIndex(count:Int, index:Int){
        this.pageCount = count
        this.pageIndex = index
        postInvalidate()
    }

    fun updatePaint(setting:(backgroundPaint: Paint, foregroundPaint:Paint)->Unit){
        setting(backgroundPaint, foregroundPaint)
        backgroundHalfWidth = backgroundPaint.strokeWidth / 2
        foregroundHalfWidth = foregroundPaint.strokeWidth / 2
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if(pageCount > 1){
            centerY = height.toFloat() / 2
            canvas?.drawLine(backgroundHalfWidth , centerY, width.toFloat() - backgroundHalfWidth, centerY , backgroundPaint)
            val length = (width.toFloat() - foregroundHalfWidth * 2) / pageCount
            var start = pageIndex * length + foregroundHalfWidth
            val end = start + length
            if(forceFromStart){
                start = foregroundHalfWidth
            }
            canvas?.drawLine(start, centerY, end, centerY, foregroundPaint)
        }
    }

}